<template>
  <view class="container">
    <!-- 顶部用户信息 -->
    <view class="user-info">
      <view class="avatar-section">
        <image class="avatar" :src="isLogin ? (config.staticUrl + (userInfo.avatar || '/static/img/default-avatar.png')) : '/static/img/default-avatar.png'" mode="aspectFill"></image>
      </view>
      <view class="info-section">
        <text class="nickname" v-if="isLogin">{{userInfo.nickName || userInfo.userName || '未设置昵称'}}</text>
        <text class="nickname" v-else @click="goToLogin">点击登录</text>
        <view class="auth-status" v-if="isLogin">
          <text :class="['status-badge', userInfo.status === '0' ? 'active' : 'inactive']">
            {{userInfo.status === '0' ? '正常' : '停用'}}
          </text>
          <text class="role-info" v-if="roles && roles.length > 0">{{roles.join(',')}}</text>
          <text class="admin-badge" v-if="userInfo.admin">管理员</text>
        </view>
        <view class="user-id" v-if="isLogin">
          <text>ID: {{userInfo.userId}}</text>
          <text class="dept-info" v-if="userInfo.dept"> | {{userInfo.dept.deptName}}</text>
          <text class="login-info" v-if="userInfo.loginIp"> | 最后登录: {{formatLoginTime(userInfo.loginDate)}}</text>
        </view>
      </view>
    </view>

    <!-- 功能列表 -->
    <view class="function-list">
      <!-- 就医记录 -->
      <!-- <view class="function-group">
        <view class="group-title">就医记录</view>
        <view class="group-content">
          <view class="function-item" @click="goToPage('history')">
            <image class="item-icon" src="/static/img/icons/history.png"></image>
            <text class="item-text">历史记录</text>
          </view>
          <view class="function-item" @click="goToPage('reports')">
            <image class="item-icon" src="/static/img/icons/report.png"></image>
            <text class="item-text">检查报告</text>
          </view>
          <view class="function-item" @click="goToPage('medication')">
            <image class="item-icon" src="/static/img/icons/medication.png"></image>
            <text class="item-text">用药记录</text>
          </view>
          <view class="function-item" @click="goToPage('expenses')">
            <image class="item-icon" src="/static/img/icons/expense.png"></image>
            <text class="item-text">费用记录</text>
          </view>
        </view>
      </view> -->

      <!-- 我的服务 -->
      <view class="function-group">
        <view class="group-title">我的服务</view>
        <view class="group-content">
          <view class="function-item" @click="goToPage('appointments')">
            <image class="item-icon" src="/static/img/icons/appointment.png"></image>
            <text class="item-text">我的预约</text>
          </view>
          <view class="function-item" @click="goToPage('companion')">
            <image class="item-icon" src="/static/img/icons/companion.png"></image>
            <text class="item-text">我的陪诊</text>
          </view>
          <view class="function-item" @click="goToPage('favorites')">
            <image class="item-icon" src="/static/img/icons/favorite.png"></image>
            <text class="item-text">智能导诊</text>
          </view>
          <view class="function-item" @click="goToPage('reviews')">
            <image class="item-icon" src="/static/img/icons/review.png"></image>
            <text class="item-text">预约挂号</text>
          </view>
        </view>
      </view>

      <!-- 工具中心 -->
      <view class="function-group">
        <view class="group-title">工具中心</view>
        <view class="group-content">
          <view class="function-item" @click="goToPage('calculator')">
            <image class="item-icon" src="/static/img/icons/calculator.png"></image>
            <text class="item-text">健康计算器</text>
          </view>
          <view class="function-item" @click="goToPage('reminder')">
            <image class="item-icon" src="/static/img/icons/schedule.png"></image>
            <text class="item-text">用药提醒</text>
          </view>
          <view class="function-item" @click="goToPage('navigation')">
            <image class="item-icon" src="/static/img/icons/navigation.png"></image>
            <text class="item-text">路线规划</text>
          </view>
          <view class="function-item" @click="goToPage('checklist')">
            <image class="item-icon" src="/static/img/icons/checklist.png"></image>
            <text class="item-text">医用工具箱</text>
          </view>
        </view>
      </view>

      <!-- 设置 -->
      <view class="function-group">
        <view class="group-title">设置</view>
        <view class="group-content">
          <view class="function-item" @click="goToPage('profile')">
            <image class="item-icon" src="/static/img/icons/profile.png"></image>
            <text class="item-text">个人信息</text>
          </view>
          <view class="function-item" @click="goToPage('security')">
            <image class="item-icon" src="/static/img/icons/security.png"></image>
            <text class="item-text">账号安全</text>
          </view>
          <view class="function-item" @click="goToPage('notification')">
            <image class="item-icon" src="/static/img/icons/notification.png"></image>
            <text class="item-text">消息通知</text>
          </view>
          <view class="function-item" @click="goToPage('about')">
            <image class="item-icon" src="/static/img/icons/about.png"></image>
            <text class="item-text">关于我们</text>
          </view>
          <view class="function-item" v-if="isLogin" @click="goToAdmin">
            <image class="item-icon" src="/static/logo.png"></image>
            <text class="item-text">管理后台</text>
          </view>
          <view class="function-item" v-if="isLogin" @click="logout">
            <image class="item-icon" src="/static/img/icons/logout.png"></image>
            <text class="item-text">退出登录</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import storage from '@/utils/storage'
import { getToken, removeToken } from '@/utils/auth'
import constant from '@/utils/constant'
import request from '@/utils/request'
import config from '@/config'

export default {
  data() {
    return {
      config,
      isLogin: false,
      userInfo: {
        avatar: '',
        nickName: '',
        userName: '',
        userId: '',
        status: '0',
        admin: false,
        dept: null,
        loginDate: '',
        loginIp: ''
      },
      roles: [],
      permissions: []
    }
  },
  onLoad() {
    this.initUserData();
  },
  methods: {
    // 初始化用户数据
    initUserData() {
      const token = getToken();
      if (!token) {
        this.clearUserData();
        return;
      }
      
      // 从storage工具获取用户信息
      this.userInfo.avatar = storage.get(constant.avatar);
      this.userInfo.nickName = storage.get(constant.nickname);
      this.userInfo.userName = storage.get(constant.name);
      this.userInfo.userId = storage.get(constant.userID);
      this.roles = storage.get(constant.roles) ? storage.get(constant.roles).split(',') : [];
      this.permissions = storage.get(constant.permissions) ? storage.get(constant.permissions).split(',') : [];
      
      // 如果有基本用户信息，则认为已登录
      if (this.userInfo.userId) {
        this.isLogin = true;
      } else {
        this.fetchUserInfo();
      }
    },
    
    // 获取用户信息
    fetchUserInfo() {
      uni.showLoading({ title: '加载中...' });
      
      request({
        url: '/system/user/profile',
        method: 'GET'
      }).then(res => {
        uni.hideLoading();
        if (res.code === 200) {
          this.isLogin = true;
          const userData = res.data || {};
          
          // 使用storage工具存储用户信息
          storage.set(constant.avatar, userData.avatar);
          storage.set(constant.nickname, userData.nickName);
          storage.set(constant.name, userData.userName);
          storage.set(constant.userID, userData.userId);
          storage.set(constant.roles, (res.roles || []).join(','));
          storage.set(constant.permissions, (res.permissions || []).join(','));
          
          // 更新本地数据
          this.userInfo = {
            ...this.userInfo,
            ...userData
          };
          this.roles = res.roles || [];
          this.permissions = res.permissions || [];
        } else {
          this.handleUnauthorized();
        }
      }).catch(err => {
        uni.hideLoading();
        this.handleUnauthorized();
        console.error('请求用户信息失败:', err);
      });
    },
    
    // 格式化登录时间
    formatLoginTime(timeStr) {
      if (!timeStr) return '';
      try {
        const date = new Date(timeStr);
        return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
      } catch (e) {
        return timeStr;
      }
    },
    
    // 处理未授权情况
    handleUnauthorized() {
      this.clearUserData();
      removeToken();
      storage.clean();
    },
    
    // 清除用户数据
    clearUserData() {
      this.isLogin = false;
      this.userInfo = {
        avatar: '',
        nickName: '',
        userName: '',
        userId: '',
        status: '0',
        admin: false,
        dept: null,
        loginDate: '',
        loginIp: ''
      };
      this.roles = [];
      this.permissions = [];
    },
    
    // 跳转到登录页面
    goToLogin() {
      uni.navigateTo({
        url: '/pages/login/login'
      });
    },
    
    // 跳转到实名认证页面
    goToRealNameAuth() {
      if (!this.isLogin) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      uni.navigateTo({
        url: '/pages/realNameAuth/realNameAuth'
      });
    },
    
    // 跳转到各个功能页面
    goToPage(page) {
      if (!this.isLogin && ['history', 'reports', 'medication', 'expenses', 'appointments', 'companion', 'favorites', 'reviews', 'profile', 'security'].includes(page)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      const pageMap = {
        'history': '/pages/medicalRecords/history',
        'reports': '/pages/medicalRecords/reports',
        'medication': '/pages/medicalRecords/medication',
        'expenses': '/pages/medicalRecords/expenses',
        'appointments': '/pages/myServices/appointments',
        'companion': '/pages/myServices/companion',
        'favorites': '/pages/aiChat/medicalAIChat',
        'reviews': '/pages/appointment/index',
        'calculator': '/pages/guide/healthcalculator',
        'reminder': '/pages/guide/reminder',
        'navigation': '/pages/medical/index',
        'checklist': '/pages/guide/medical',
        'profile': '/pages/my/my',
        'security': '/pages/my/security',
        'notification': '/pages/index/notification',
        'about': '/pages/about/about'
      };
      
      if (pageMap[page]) {
        uni.navigateTo({
          url: pageMap[page]
        });
      } else {
        uni.showToast({
          title: '功能开发中',
          icon: 'none'
        });
      }
    },
    
    // 退出登录
    logout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            this.clearUserData();
            uni.removeStorageSync('token');
            uni.removeStorageSync('userInfo');
            uni.removeStorageSync('roles');
            uni.removeStorageSync('permissions');
            uni.showToast({
              title: '已退出登录',
              icon: 'success'
            });
          }
        }
      });
    },
    
    // 跳转到后台管理系统
    goToAdmin() {
      // 开发环境下的后台地址
      const adminUrl = 'http://localhost:81';
      
      // 使用web-view组件打开网页
      uni.navigateTo({
        url: `/pages/webview/index?url=${encodeURIComponent(adminUrl)}`
      });
    }
  },
  onShow() {
    this.initUserData();
  }
}
</script>

<style>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.user-info {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.avatar-section {
  margin-right: 30rpx;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 2rpx solid #eee;
}

.info-section {
  flex: 1;
}

.nickname {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  display: block;
}

.nickname[v-if="!isLogin"] {
  color: #007aff;
}

.auth-status {
  font-size: 24rpx;
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
  flex-wrap: wrap;
}

.status-badge {
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
}

.status-badge.active {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.status-badge.inactive {
  background-color: #ffebee;
  color: #c62828;
}

.user-id {
  font-size: 24rpx;
  color: #999;
  display: flex;
  flex-wrap: wrap;
}

.role-info {
  margin-left: 10rpx;
  color: #666;
  font-size: 24rpx;
}

.admin-badge {
  margin-left: 10rpx;
  padding: 4rpx 12rpx;
  background-color: #f0f7ff;
  color: #1890ff;
  border-radius: 20rpx;
  font-size: 22rpx;
}

.dept-info, .login-info {
  color: #999;
  font-size: 24rpx;
  margin-left: 10rpx;
}

.function-list {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 0 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.function-group {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.function-group:last-child {
  border-bottom: none;
}

.group-title {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 20rpx;
}

.group-content {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.function-item {
  width: 25%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30rpx;
}

.item-icon {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 10rpx;
}

.item-text {
  font-size: 24rpx;
  color: #333;
}

/* 退出登录按钮特殊样式 */
.function-item:last-child .item-text {
  color: #e64340;
}
</style>